package com.blog.cloud.core.utils;

import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * Bean复制工具类
 *
 * @author 龙茶清欢
 * @since 2022-11-26 12:30:55
 */
public class BeanCopyUtil {

    @SneakyThrows
    public static <K, V> V singleCopy(K source, Class<V> target) {
        Assert.notNull(source, "source不能为空");
        Assert.notNull(target, "target不能为空");
        V instance = target.getDeclaredConstructor().newInstance();
        BeanUtils.copyProperties(source, instance);
        return instance;
    }

    @SneakyThrows
    public static <K, V> List<V> listCopy(List<K> source, Class<V> target) {
        Assert.noNullElements(source, "source不能为空,且元素也不能为空");
        Assert.notNull(target, "target不能为空");
        List<V> targetList = new ArrayList<>();
        source.forEach(item -> {
            V instance;
            try {
                instance = target.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(item, instance);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            targetList.add(instance);
        });
        return targetList;
    }
}

// Bean复制时必须保证source和target中对应的需要复制的字段数据类型和名称都一致